"""搜索组件模块"""

from PySide6.QtWidgets import QWidget, QHBoxLayout, QLineEdit, QPushButton, QLabel
from PySide6.QtCore import Qt, Signal, QPropertyAnimation, QEasingCurve, QTimer
from PySide6.QtGui import QFont, QIcon, QPixmap, QPainter, QPen


class SearchWidget(QWidget):
    """可收缩的搜索组件"""
    
    # 信号定义
    search_requested = Signal(str)  # 搜索请求信号
    search_cleared = Signal()  # 搜索清除信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.is_expanded = False  # 默认收缩状态
        self.animation = None
        self.collapse_timer = QTimer()  # 延迟收缩定时器
        self.collapse_timer.setSingleShot(True)
        self.collapse_timer.timeout.connect(self.collapse_search_area)
        self.setup_ui()
        self.setup_connections()
    
    def setup_ui(self):
        """设置UI"""
        # 不设置固定高度，让父容器决定
        # self.setFixedHeight(35)  # 注释掉固定高度
        
        layout = QHBoxLayout()
        layout.setContentsMargins(2, 2, 2, 2)  # 减少边距适应小空间
        layout.setSpacing(0)
        
        # 搜索图标按钮（始终显示）
        self.search_icon_button = QPushButton()
        self.search_icon_button.setFixedSize(20, 20)  # 减小尺寸
        self.search_icon_button.setIcon(self.create_search_icon())
        self.search_icon_button.setToolTip("搜索剪切板内容 (Ctrl+F)")
        self.search_icon_button.setStyleSheet("""
            QPushButton {
                background-color: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 3px;
                padding: 2px;
            }
            QPushButton:hover {
                background-color: #e9ecef;
                border-color: #007bff;
            }
            QPushButton:pressed {
                background-color: #dee2e6;
            }
        """)
        
        # 可展开的搜索区域
        self.search_area = QWidget()
        self.search_area.setFixedHeight(20)  # 适应title_bar高度
        self.search_area.hide()  # 默认隐藏
        
        search_area_layout = QHBoxLayout()
        search_area_layout.setContentsMargins(0, 0, 0, 0)
        search_area_layout.setSpacing(3)  # 减少间距
        
        # 搜索框
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("搜索...")
        self.search_input.setFixedWidth(150)  # 减小宽度
        self.search_input.setStyleSheet("""
            QLineEdit {
                border: 1px solid #dee2e6;
                border-radius: 3px;
                padding: 2px 6px;
                font-size: 11px;
                background-color: #ffffff;
            }
            QLineEdit:focus {
                border-color: #007bff;
                outline: none;
            }
        """)
        
        # 搜索按钮
        self.search_button = QPushButton("搜索")
        self.search_button.setFixedSize(40, 20)  # 减小尺寸
        self.search_button.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                padding: 1px 4px;
                border-radius: 3px;
                font-size: 10px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
        """)
        
        # 清除按钮
        self.clear_button = QPushButton("清除")
        self.clear_button.setFixedSize(40, 20)  # 减小尺寸
        self.clear_button.setStyleSheet("""
            QPushButton {
                background-color: #6c757d;
                color: white;
                border: none;
                padding: 1px 4px;
                border-radius: 3px;
                font-size: 10px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #5a6268;
            }
            QPushButton:pressed {
                background-color: #495057;
            }
        """)
        
        # 收缩按钮 - 隐藏
        # self.collapse_button = QPushButton("×")
        # self.collapse_button.setFixedSize(16, 20)  # 减小尺寸
        # self.collapse_button.setToolTip("收缩搜索栏")
        # self.collapse_button.setStyleSheet("""
        #     QPushButton {
        #         background-color: #f8f9fa;
        #         color: #6c757d;
        #         border: 1px solid #dee2e6;
        #         border-radius: 3px;
        #         font-size: 12px;
        #         font-weight: bold;
        #     }
        #     QPushButton:hover {
        #         background-color: #e9ecef;
        #         color: #495057;
        #     }
        # """)
        
        search_area_layout.addWidget(self.search_input)
        search_area_layout.addWidget(self.search_button)
        search_area_layout.addWidget(self.clear_button)
        # search_area_layout.addWidget(self.collapse_button)  # 不添加收缩按钮
        
        self.search_area.setLayout(search_area_layout)
        
        # 主布局
        layout.addStretch()  # 推到右边
        layout.addWidget(self.search_icon_button)
        layout.addWidget(self.search_area)
        
        self.setLayout(layout)
    
    def create_search_icon(self) -> QIcon:
        """创建搜索图标"""
        pixmap = QPixmap(16, 16)
        pixmap.fill(Qt.transparent)
        
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(Qt.black, 2))
        
        # 绘制放大镜
        painter.drawEllipse(2, 2, 8, 8)  # 圆形
        painter.drawLine(9, 9, 13, 13)   # 手柄
        
        painter.end()
        return QIcon(pixmap)
    
    def setup_connections(self):
        """设置信号连接"""
        self.search_icon_button.clicked.connect(self.toggle_search_area)
        self.search_button.clicked.connect(self.perform_search)
        self.clear_button.clicked.connect(self.clear_search)
        # self.collapse_button.clicked.connect(self.collapse_search_area) # 不连接收缩按钮
        self.search_input.returnPressed.connect(self.perform_search)  # 回车键搜索
    
    def toggle_search_area(self):
        """切换搜索区域显示/隐藏"""
        if self.is_expanded:
            self.collapse_search_area()
        else:
            self.expand_search_area()
    
    def expand_search_area(self):
        """展开搜索区域"""
        if self.is_expanded:
            return
        
        # 停止可能正在运行的收缩定时器
        if self.collapse_timer.isActive():
            self.collapse_timer.stop()
            
        self.is_expanded = True
        self.search_area.show()
        
        # 创建宽度动画
        self.animation = QPropertyAnimation(self.search_area, b"maximumWidth")
        self.animation.setDuration(250)
        self.animation.setStartValue(0)
        self.animation.setEndValue(235)  # 调整为新的总宽度 (150+40+40+间距，不包括收缩按钮)
        self.animation.setEasingCurve(QEasingCurve.OutCubic)
        self.animation.start()
        
        # 聚焦到搜索框
        self.search_input.setFocus()
    
    def collapse_search_area(self):
        """收缩搜索区域"""
        if not self.is_expanded:
            return
            
        self.is_expanded = False
        
        # 创建宽度动画
        self.animation = QPropertyAnimation(self.search_area, b"maximumWidth")
        self.animation.setDuration(250)
        self.animation.setStartValue(235)  # 调整为新的总宽度
        self.animation.setEndValue(0)
        self.animation.setEasingCurve(QEasingCurve.InCubic)
        
        # 动画完成后隐藏
        self.animation.finished.connect(self._on_collapse_finished)
        self.animation.start()
    
    def _on_collapse_finished(self):
        """收缩动画完成后的处理"""
        self.search_area.hide()
        if self.animation:
            self.animation.finished.disconnect()
    
    def perform_search(self):
        """执行搜索"""
        # 如果有延迟收缩定时器在运行，停止它
        if self.collapse_timer.isActive():
            self.collapse_timer.stop()
            
        search_text = self.search_input.text().strip()
        if search_text:
            self.search_requested.emit(search_text)
        else:
            self.clear_search()
    
    def clear_search(self):
        """清除搜索"""
        self.search_input.clear()
        self.search_cleared.emit()
        # 延迟2秒后自动收缩，给用户时间继续搜索
        self.collapse_timer.start(2000)
    
    def get_search_text(self) -> str:
        """获取当前搜索文本"""
        return self.search_input.text().strip()
    
    def set_search_text(self, text: str):
        """设置搜索文本"""
        self.search_input.setText(text)
        if text and not self.is_expanded:
            self.expand_search_area()
    
    def focus_search(self):
        """聚焦到搜索框"""
        if not self.is_expanded:
            self.expand_search_area()
        else:
            self.search_input.setFocus()
            self.search_input.selectAll()
    
    def is_searching(self) -> bool:
        """是否正在搜索"""
        return bool(self.search_input.text().strip()) 